package com.fingard.dsp.bank.directbank.allinpay02;

import java.util.TreeMap;

import com.alibaba.fastjson.JSONObject;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.allinpay02.util.SybUtil;
import com.fingard.dsp.bank.directbank.bankInterface.ICloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.CloseOrderState;
import com.fingard.dsp.bank.reqrespobj.closeorder.ReqCloseOrder;
import com.fingard.dsp.bank.reqrespobj.closeorder.RetAtsCloseOrder;
import com.fingard.text.StringHelper;

public class AllInPay02CloseOrder extends AllInPay02Base implements ICloseOrder {
	public RetAtsCloseOrder closeOrder(ReqCloseOrder p_req) {
		RetAtsCloseOrder retAts = new RetAtsCloseOrder(p_req.reqHeader);
		retAts.rdSeq = p_req.rdSeq;

		try {
			ActSetItem actItem = getBankConfig().getActSetItemByAny(p_req.ownAct, p_req.merchantId,	p_req.appId, "unifiedorder");
			if (actItem != null) {
				TreeMap<String, String> params = new TreeMap<String, String>();
				
				params.put("cusid", actItem.merchantId);
				params.put("appid", actItem.appId); 
				params.put("version", "11");
				params.put("oldreqsn", p_req.rdSeq);
				params.put("oldtrxid", "");
				params.put("randomstr", get_nonce_str()); 
				params.put("sign", SybUtil.sign(params, actItem.saltKey)); 
				
				String tmpRetStr = sendUnifiedToBank(params, bankFront.getUrl("unifiedOrderClose"));
				
				if (StringHelper.hasAnyChar(tmpRetStr)) {
					if (tmpRetStr.indexOf("{") >= 0) {
						JSONObject respJson = JSONObject.parseObject(tmpRetStr);
						
						String respCode = respJson.getString("retcode");
						if ("SUCCESS".equals(respCode)) {
							retAts.respCode = "0";
							retAts.respInfo = respJson.getString("retmsg");
							
							String tranStatus = respJson.getString("trxstatus"); /* 0000-交易成功关闭 ,其余关闭失败 */
							if (StringHelper.hasAnyChar(tranStatus)) {
								if ("0000".equals(tranStatus)) {
									retAts.closeState = CloseOrderState.Close_Success;
								} else {
									retAts.closeState = CloseOrderState.Close_Fail;
									retAts.errorCode = tranStatus; 
									retAts.errorMsg = respJson.getString("errmsg");
								}
							}
						} else {
							retAts.respCode = "-1";
							retAts.respInfo = respJson.getString("retmsg");
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = tmpRetStr;
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "通联响应数据为空";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respInfo = "未找到账号[" + p_req.ownAct + "]商户配置信息";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}
